<?php
	ini_set('session.bug_compat_warn', 0);
	ini_set('session.bug_compat_42', 0);
	require(dirname(__FILE__). '/debug/Debug.php');
	function getAvatar($id = null,$size = "40-40") {
		$sql = "select id_image,id_inscrit,image_nom, image_description, case when image_avatar=1 then 1 else 0 end as image_avatar from lyad_leeloo_images.t_image where id_inscrit=".$id." AND date_image_supr is null AND image_avatar=1 ORDER BY date_insertion DESC";
		$avatar = callProcedure($sql);
		$_avatar = null;
		if(!empty($avatar)){
			$_avatar = $avatar[0]['image_nom'];
		}
		return DM_LYAD."/upload/user/files/images_lyad_tmp/fill/$size/".$_avatar;
	}
	function curPageURL() {
		$pageURL = 'http';
		$HTTPS = !empty($_SERVER["HTTPS"]) ? $_SERVER["HTTPS"] : null;
		if ($HTTPS == "on") {
			$pageURL .= "s";
		}
		$pageURL .= "://";
		if ($_SERVER["SERVER_PORT"] != "80") {
			$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
		} else {
			$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
		}
		return $pageURL;
	}
	/**
	 * This action used assign text on image
	 **/
	function watermarkImage($SourceFile, $WaterMarkText,$points = array(),$type = "png") { 

		// load the image from the file specified:
		switch($type){
			case "jpeg":
				$im = imagecreatefromjpeg($SourceFile);
			break;	
			default:
				
				$im = imagecreatefrompng($SourceFile);
			break;
		}
		
		// if there's an error, stop processing the page:
		if(!$im)
		{
			die("File not found");
		}
		 
		// define some colours to use with the image
		$yellow = imagecolorallocate($im, 255, 255, 0);
		$black = imagecolorallocate($im, 0, 0, 0);
		$w = imagecolorallocate($im, 255,0,0);
		
		 
		// get the width and the height of the image
		$width = imagesx($im);
		$height = imagesy($im);
		 
		// draw a black rectangle across the bottom, say, 20 pixels of the image:
		// imagefilledrectangle($im, 0, ($height-20) , $width, $height, $w);
		 
		// now we want to write in the centre of the rectangle:
		$font = 14;
		$text = $WaterMarkText; // store the text we're going to write in $text
		// calculate the left position of the text:
		$leftTextPos = ( $width - imagefontwidth($font)*strlen($text) )/2;

		// finally, write the string:
		if(empty($points)){
			imagestring($im, $font, $leftTextPos, $height-35, $text, $black);
		}else{
			imagestring($im, $font, $points[0], $points[1], $text, $black);
		}
		 
		// output the image
		// tell the browser what we're sending it
		header('Content-type: image/png');
		// output the image as a png
		imagepng($im);
		 
		// tidy up
		imagedestroy($im);

		

	}
	/**
	 * This function used call procedure to mysql
	 * Used: $result = callProcedure($sql,true,array('@id_skin','@application','@titre','@ville','@langue'));
	 * Or: $result = callProcedure($sql);
	 */
	
	function callProcedure($arrSql = null,$return = false,$dataReturn = array(),$getMultipleRes = false,$hand = false){

		$is_array  = false;
		$sql = $arrSql;
		$sql0 = null;
		$multipleSQL = false;
		if(is_array($arrSql)){
			$sql = end($arrSql);
			$sql0 = $arrSql[0];
			$multipleSQL = true;
		}
		
		if($return == false){
			
			try{
				$result = mysql_query($sql,connection());
				if (!$result) {
					die('Invalid query: ' . mysql_error()." - SQL: {$sql}");
				}else{
					$data = array();
					
					if(@is_resource($result)){
						
					// }else{
					
						$numResults = mysql_num_rows($result);
						if ($numResults > 0) {
							while ($row = mysql_fetch_assoc($result)) {
								
								$data[] = $row;
								//return $desc;
							}
						}
						
						
					}
					return $data;
				}
			}catch(Exception $e){
				echo $e->getMessage()."<br>";
				echo $sql."<br>";
				die('Invalid query: ' . mysql_error()." - SQL: {$sql}");
			}
			
		}else{
			
			
			$mydb = connection(1);
			
			
			if(count($arrSql) > 2 && $multipleSQL){
				foreach($arrSql as $k=>$s){
					
					if($k != count($arrSql) - 1):
						//echo $s."<br>";
						$proc = $mydb->prepare($s);
						$proc->execute();
					endif;

				}
			}else{
				if($sql0!=null){
					$proc = $mydb->prepare($sql0);
					$proc->execute();
				}
			}
			
			//echo $sql;
			$proc = $mydb->prepare($sql);
			try{
				$proc->execute();
			}catch(Exception $e){
				echo $e->getMessage()."<br>";
				echo $sql."<br>";
				die('Invalid query: ' . mysql_error()." - SQL: {$sql}");
			}
			
			
			if($hand) return $proc;
			/**
			 * This partial used get multiple result for procedure
			 **/
			if($getMultipleRes){
				$maxRs = 40;
				$data = array();
				$cnt = 0;
				if(!empty($dataReturn)){
					foreach($dataReturn as $key=>$value){
						$row = $proc->fetchAll(PDO::FETCH_ASSOC);
						$data[$value] = $row;
						if($cnt != $maxRs){
							$proc->nextRowset();
						}
						$cnt++;
					}
				}else{
					
				}
				
				$proc->closeCursor();
				
				return $data;
			}else{
			
				if(!empty($dataReturn)){
					$strQuery = "SELECT";
					$cnt = 0;
					foreach($dataReturn as $key=>$data){
						if( count($dataReturn)-1 == $cnt){
							$strQuery.= " {$data}";
						}else{
							$strQuery.= " {$data},";
						}
						$cnt++;
						
					}
					
					$result = $mydb->query($strQuery)->fetch(PDO::FETCH_ASSOC);
					$proc->closeCursor();
					return $result;
				}else{
					$proc->closeCursor();
					return array();
				}
			}
			
		}
	}
	
	// cette fonction cree un code unique utilise pour eviter de resortir un id d'un base (plus rapide permet de rentrer un id en mode asynchrone)
	// cree un num de 17 chiffres ,il existe 999999 codes aleatoires toutes les milisecondes(tres peux de chance de doublons)

	function give_id_ord(){
		$id_ord = !empty($_COOKIE['id_ord']['id_ord']) ? ($_COOKIE['id_ord']['id_ord']) : null;
		if(empty($id_ord)){
			$_SESSION['id_ord'] = $id_ord;
		}else{
			$y = substr(date('Y'),-1); 											//dernnier chiffre de l'ann?e 2004 -->4
			$j = date('z');
			$t = (date('h')*60*60)+(date('i')*60)+date('s'); 					//ex: t="1234"-->0123400 ou t="1234,5"-->0123450 ou t="1234,02"-->0123402
			if(strpos($t, ",")===false){
				$t = substr("00000".$t."00", -7);		//si il n'y a pas de miliseconde(je ne sais pas si ca arrive?)
			}else{
				$s = explode(",", $t);
				$t = substr("00000".$s[0], -5).substr($s[1]."00", 0,2);		//timer() = nb seconde depuis minuit 3600secondes *24h =86400,00 secondes max  (on suprime la virgule)
				
			}
			// randomize
			$rd = (10000000 * rand());
			$a = substr("000000".$rd,-6);										//nb aleat entre 000000-->999999
			$id_ord = $y.$j.$t.$a;

			/** on stock id dans un cookies
			 * date+360 perime jamais - experted until 01/01/2037
			 * path: "/" permet de voir le cookies de tous les repertoire	response.cookies("id_ord").domain = ".lyad.com"			'fonctionne aussi pour les subdomains
			 */
			setcookie("id_ord['id_ord']",$id_ord,strtotime("01/01/2037"),"/");	
			//response.cookies("id_ord").domain = ".lyad.com"			'fonctionne aussi pour les subdomains
			$_SESSION["id_ord"] = $id_ord;
		}
	}
	function dump($obj,$isExit = true) {
		Debug::d($obj,10,true);
		if ($isExit) exit();	
	}
	function geo(){
		$ip 				= $_SERVER["REMOTE_ADDR"];
		if(!empty($_SERVER["REMOTE_ADDR"])){
			if($ip == "127.0.0.1"){
				$geo = @file_get_contents('http://ipinfo.io');
			}else{
				$geo = @file_get_contents('http://ipinfo.io/'.$ip.'/json');
			}
		}else{
			$geo = @file_get_contents('http://ipinfo.io');
		}
		
		$arrGeo = (array) @json_decode($geo);
		$arrLatLng = array();
		if(!empty($arrGeo['loc'])){
			$arrLatLng = explode(",",$arrGeo['loc']);
		}
		$lat = !empty($arrLatLng[0]) ? $arrLatLng[0] : "0.00000000";
		$lng = !empty($arrLatLng[1]) ? $arrLatLng[1] : "0.00000000";
		$arrGeo['latitude'] = !empty($arrLatLng[0]) ? $arrLatLng[0] : "0.00000000";
		$arrGeo['longitude'] = !empty($arrLatLng[1]) ? $arrLatLng[1] : "0.00000000";
		
		if(!empty($arrGeo['bogon'])){
			$arrGeo = array(
				"ip"=> "113.160.226.120",
				"hostname"=> "No Hostname",
				"city"=> "Hanoi",
				"region"=> "Ha Noi",
				"country"=> "VN",
				"loc"=> "21.033299999999997,105.85000000000002",
				"latitude"=>"21.033299999999997",
				"longtitude"=>"105.85000000000002",
				"org"=> "AS45899 VNPT Corp"
			);
		}
		$arrGeo['ip']='213.144.202.'.rand(1,255);
		$arrGeo['loc']='48.7916,2.6475';
		$arrGeo['latitude']='48.7916';
		$arrGeo['longtitude']='2.6475';
		$arrGeo['city']='Paris';
		$arrGeo['country']='FR';
		$arrGeo['codepostal']=38100;
		
		return (object) $arrGeo;
	}
	
	function CUrl(){
		// To do
		return null;
	}
	

	function htmldump($variable, $height="14em") {
		echo "<pre style=\"border: 1px solid red; height: {$height}; overflow: auto; margin: 0.5em;\">";
			var_dump($variable);
		echo "</pre>\n";
	}
   
		
		
	function otherDiffDate($out_in_array=false,$end=null){
		if($end == null) $end = '2020-06-09 10:30:00';
		
		$end = date("Y-m-d",strtotime($end));
		
        $intervalo = date_diff(date_create(), date_create($end));
        $out = $intervalo->format("Years:%Y,Months:%M,Days:%d,Hours:%H,Minutes:%i,Seconds:%s");
        if(!$out_in_array)
            return $out;
        $a_out = array();
        array_walk(explode(',',$out),
        function($val,$key) use(&$a_out){
            $v=explode(':',$val);
            $a_out[$v[0]] = $v[1];
        });
        return $a_out;
	}
	//rajout marqueur pour stats mise en relation sur index direct
	function insert_marqueur($psMarqueur){

		if (!empty($_SESSION[$psMarqueur."_marqueur"]) && $_SESSION[$psMarqueur."_marqueur"]==1){
				return false;
		}
		try{
			
			callProcedure("CALL p_insert_t_marqueur_evolution('".$psMarqueur."',null,'".date("Y-m-d")."',null,null)");
		}catch(Exception $e){
			throw new Exception($e->getMessage());
		}

		$_SESSION[$psMarqueur."_marqueur"]=1;

	}
	
	function  marq_mail_lu() {
		// ' attention un unique identifier incomplet peut creer des erreurs sur le client
		$id_email_send = !empty($_REQUEST["id_email_send"]) ? $_REQUEST["id_email_send"] : null;
		if (empty($id_email_send))
			return;
		// 'session("id_email_send")=id_email_send
		callProcedure("call p_valid_image_mail('".$id_email_send."')");
					
	}
	
	function getMeta(){
		
		
		
	}
	function datediff($date1,$date2){
		$diff=date_diff($date1,$date2);
		return $diff->format("%R%a");
	}

	function iif($expr, $truepart, $falsepart) {
		if($expr) 
			return $truepart;
		else
			return $falsepart;
		
	}
	function viif($expr, $truepart, $falsepart) {
		return iif($expr, $truepart, $falsepart);
	}
?>